# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from django.conf import settings

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '80000399': {  # 离线付 zs 3% 100-5000  支付宝h5
        'API_KEY': '3a51b176f38cb81e2129c55464e71cc7',
        'gateway': 'http://47.103.32.51/api/pay',
        'query_gateway': 'http://47.103.32.51/api/pay/query',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_pay_type(service):
    if service == 'bank':  # 网银支付
        return 'bank'
    elif service == 'bank_swift':  # 网银快捷
        return 'bank_swift'
    elif service == 'wx_qr':  # 微信扫码支付
        return 'wx_qr'
    elif service == 'wx_gzh':  # 微信公众号支付
        return 'wx_gzh'
    elif service == 'wx_h5':  # 微信WAP网页支付
        return 'wx_h5'
    elif service == 'wx_app':  # 微信APP支付
        return 'wx_app'
    elif service == 'alipay_app':  # 支付宝APP支付
        return 'alipay_app'
    elif service == 'alipay_h5':  # 支付宝WAP网页支付
        return 'alipay_h5'
    elif service == 'alipay_web':  # 支付宝PC网页支付
        return 'alipay_web'
    elif service == 'alipay_qr':  # 支付宝扫码支付
        return 'alipay_qr'
    elif service == 'qq_qr':  # QQ钱包扫码
        return 'qq_qr'
    elif service == 'qq_h5':  # QQ钱包H5
        return 'qq_h5'
    elif service == 'jd_h5':  # 京东支付H5
        return 'jd_h5'
    elif service == 'cloud_flash':  # 云闪付
        return 'union_qr'
    return 'alipay_app'


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_sign(parameter, key):
    s = 'app_id=' + parameter['app_id'] + 'notify_url=' + parameter['notify_url'] + 'order_no=' \
        + parameter['order_no'] + 'pay_amt=' + parameter['pay_amt'] + 'pay_cur=' + parameter['pay_cur'] \
        + 'pay_type=' + parameter['pay_type'] + 'return_url=' + parameter['return_url'] \
        + parameter['ts'] + str(key)
    return _gen_sign(s)


def verify_sign(params, key):
    sign = params['sign']
    s = 'app_id=' + params['app_id'] + 'is_success=' + params['is_success'] + 'order_no=' \
        + params['order_no'] + 'pay_actual_amt=' + params['pay_actual_amt'] \
        + params['ts'] + str(key)
    calculated_sign = _gen_sign(s)
    if sign.lower() != calculated_sign:
        _LOGGER.info("lixianfu2pay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)
    else:
        return calculated_sign


def notify_sign(parameter, key):
    s = 'app_id=' + parameter['app_id'] + 'order_no=' + parameter['order_no'] \
        + parameter['ts'] + key
    return _gen_sign(s)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>document.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    """ 创建订单 """
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        ('app_id', app_id),
        ('order_no', str(pay.id)),
        ('pay_amt', '%.2f' % pay_amount),
        ('pay_cur', 'CNY'),
        ('goods_name', 'charge'),
        ('goods_num', '1'),
        ('goods_cat', 'money'),
        ('goods_desc', 'nice'),
        ('return_url',
         '{}/pay/api/{}/lixianfu2pay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('notify_url', '{}/pay/api/{}/lixianfu2pay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('user_id', str(pay.user_id)),
        ('username', str(pay.id)),
        ('pay_type', _get_pay_type(service)),
        ('state', ''),
        ('ts', str(int(round(time.time() * 1000)))),
        ('sign', 'MD5')
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("lixianfu2pay create charge data: %s, order_id is: %s ", json.dumps(parameter_dict),
                 parameter_dict['order_no'])
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# SUCCESS
def check_notify_sign(request, app_id):
    data = dict(request.GET.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("lixianfu2pay notify data: %s, order_id is: %s", data, data['order_no'])
    verify_sign(data, api_key)
    pay_id = data['order_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('lixianfu2pay event does not contain pay ID')

    pay = order_db.get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('lixianfu2pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['is_success'])
    trade_no = ''
    total_fee = float(data['pay_actual_amt'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == '1' and total_fee > 0.0:
        _LOGGER.info('lixianfu2pay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('app_id', app_id),
        ('order_no', str(pay_id)),
        ('ts', str(int(time.time()))),
    ))
    parameter_dict['sign'] = notify_sign(parameter_dict, api_key)
    url = _get_query_gateway(app_id) + '?app_id=' + app_id + '&order_no=' + str(pay_id) + '&ts=' \
          + parameter_dict['ts'] + '&sign=' + parameter_dict['sign']
    _LOGGER.info("lixianfu2pay query data: %s, order_id is: %s ", url, parameter_dict['order_no'])
    response = requests.get(url, timeout=3)
    _LOGGER.info("lixianfu2pay query  rsp data: %s,%s", response.text, response.url)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['status'])
        trade_no = str(data['order_no'])
        total_fee = float(pay_order.total_fee)
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        # 10：订单状态，1: 付成功, 0:未 付, -1:订单失败
        if trade_status == '1':
            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('lixianfu2pay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('lixianfu2pay data error, status_code: %s', response.status_code)
